<template>
  <div id="user-show">
    <div class="user-profile">
      <el-avatar :size="90" :src="showingUser.avatar"></el-avatar>
      <h2 class="nickname">{{ showingUser.nickname }}</h2>
      <UserNav/>
    </div>
    <router-view v-if="Object.keys(showingUser).length"/>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import UserNav from './UserNav';
import * as format from '../format';

export default {
  name: 'UserShow',
  components: { UserNav },
  data() {
    return {
      isLoading: false, // 正在加载用户数据
    };
  },
  computed: {
    ...mapState(['showingUser']),
    // 当前查看的用户id
    userId() { return this.$route.params.userId; },
  },
  methods: {
    ...mapActions(['setShowingUser', 'removeShowingUser']),
    // 加载用户数据
    loadUser() {
      this.isLoading = true;
      this.$api.users.show({ userId: this.userId })
        .then((res) => { this.setShowingUser(format.formatUser(res.data)); })
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
  },
  created() {
    this.loadUser();
  },
  destroyed() {
    this.removeShowingUser();
  },
  watch: {
    // 监听当前路由的用户id，切换时重新加载用户数据
    userId() {
      this.removeShowingUser();
      this.loadUser();
    },
  },
};
</script>

<style lang="scss">
#user-show {
  .user-profile {
    padding-top: 1.5rem;
    background-color: #fafafa;
    border-bottom: 1px solid #e5e5e5;
    text-align: center;

    .nickname { font-weight: normal; }
  }
}
</style>
